package buaa.leetcode.String;

public class longestPrefix {
	public static String LongestCommonPrefix1(String[] strs){
		/*int minLen = strs[0].length();
		for(int i=1;i<strs.length;i++){
			if(strs[i].length()<minLen){
				minLen = strs[i].length();
			}	
		}*/
		if(strs.length == 0){return "";}
		if(strs.length == 1){return strs[0];}
		String result = strs[0];
		for(int i=1;i<strs.length;i++){
			if(strs[i].length()<1 || strs[i].length()<1){return "";}
			result = LongPrefix(result,strs[i]);
		}
		
		return result;
	}
	public static String LongPrefix(String s1,String s2){
		if(s1.length()<1||s1.length()<1){
			return "";
		}
		int minLen = (s1.length() > s2.length())?s2.length():s1.length();
		
		StringBuilder prefix = new StringBuilder();
		for(int i = 0;i< minLen;i++){
			if(s1.charAt(i) == s2.charAt(i)){
				prefix = prefix.append(s1.charAt(i));
			}else{
				break;
			}
		}
		return prefix.toString();
	}
	public static String LongestCommonPrefix2(String[] strs){
		if(strs.length == 0){return "";}
		if(strs.length == 1){return strs[0];}
		int minLen = strs[0].length();
		for(int i=1;i<strs.length;i++){
			if(strs[i].length()<minLen){
				minLen = strs[i].length();
			}	
		}
		if(minLen < 1){return "";}
		StringBuilder result = new StringBuilder();
		for(int index = 0 ;index<minLen;index++){
			for(int i = 0;i<strs.length-1;i++){
				if(strs[i].charAt(index) != strs[i+1].charAt(index)){
					return result.toString();
				}
			}
			result = result.append(strs[0].charAt(index));
		}
		return result.toString();
}
}
